package com.carrental.vehicle.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.carrental.common.exception.BusinessException;
import com.carrental.vehicle.entity.Vehicle;
import com.carrental.vehicle.entity.VehicleBrand;
import com.carrental.vehicle.entity.VehicleSeries;
import com.carrental.vehicle.mapper.VehicleBrandMapper;
import com.carrental.vehicle.mapper.VehicleMapper;
import com.carrental.vehicle.mapper.VehicleSeriesMapper;
import com.carrental.vehicle.service.VehicleSeriesService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 车辆系列服务实现类
 */
@Service
@RequiredArgsConstructor
public class VehicleSeriesServiceImpl extends ServiceImpl<VehicleSeriesMapper, VehicleSeries> implements VehicleSeriesService {

    private final VehicleBrandMapper vehicleBrandMapper;
    private final VehicleMapper vehicleMapper;

    /**
     * 根据ID获取系列
     *
     * @param id 系列ID
     * @return 系列信息
     */
    @Override
    public VehicleSeries getSeriesById(Long id) {
        VehicleSeries series = getById(id);
        if (series == null) {
            throw new BusinessException("系列不存在");
        }
        return series;
    }

    /**
     * 保存或更新系列
     *
     * @param vehicleSeries 系列信息
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveOrUpdateSeries(VehicleSeries vehicleSeries) {
        // 检查品牌是否存在
        VehicleBrand brand = vehicleBrandMapper.selectById(vehicleSeries.getBrandId());
        if (brand == null) {
            throw new BusinessException("品牌不存在");
        }
        
        // 检查系列名称是否重复
        LambdaQueryWrapper<VehicleSeries> queryWrapper = new LambdaQueryWrapper<VehicleSeries>()
                .eq(VehicleSeries::getName, vehicleSeries.getName())
                .eq(VehicleSeries::getBrandId, vehicleSeries.getBrandId())
                .eq(VehicleSeries::getDeleted, 0);
        
        if (vehicleSeries.getId() != null) {
            queryWrapper.ne(VehicleSeries::getId, vehicleSeries.getId());
        }
        
        long count = count(queryWrapper);
        if (count > 0) {
            throw new BusinessException("该品牌下系列名称已存在");
        }
        
        LocalDateTime now = LocalDateTime.now();
        
        if (vehicleSeries.getId() == null) {
            // 新增
            vehicleSeries.setCreateTime(now);
            vehicleSeries.setUpdateTime(now);
            vehicleSeries.setDeleted(0);
            return save(vehicleSeries);
        } else {
            // 更新
            vehicleSeries.setUpdateTime(now);
            return updateById(vehicleSeries);
        }
    }

    /**
     * 删除系列
     *
     * @param id 系列ID
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteSeriesById(Long id) {
        // 检查系列是否存在
        VehicleSeries series = getById(id);
        if (series == null) {
            throw new BusinessException("系列不存在");
        }
        
        // 检查是否有关联的车辆
        long count = vehicleMapper.selectCount(new LambdaQueryWrapper<Vehicle>()
                .eq(Vehicle::getSeriesId, id)
                .eq(Vehicle::getDeleted, 0));
        
        if (count > 0) {
            throw new BusinessException("该系列下存在车辆，不能删除");
        }
        
        return removeById(id);
    }

    /**
     * 分页查询系列
     *
     * @param page   分页参数
     * @param series 查询条件
     * @return 分页结果
     */
    @Override
    public Page<VehicleSeries> pageSeries(Page<VehicleSeries> page, VehicleSeries series) {
        LambdaQueryWrapper<VehicleSeries> queryWrapper = new LambdaQueryWrapper<>();
        
        queryWrapper.eq(series.getBrandId() != null, VehicleSeries::getBrandId, series.getBrandId())
                .like(series.getName() != null, VehicleSeries::getName, series.getName())
                .eq(VehicleSeries::getDeleted, 0)
                .orderByDesc(VehicleSeries::getCreateTime);
        
        Page<VehicleSeries> seriesPage = page(page, queryWrapper);
        
        // 查询品牌名称
        for (VehicleSeries s : seriesPage.getRecords()) {
            VehicleBrand brand = vehicleBrandMapper.selectById(s.getBrandId());
            if (brand != null) {
                s.setBrandName(brand.getName());
            }
        }
        
        return seriesPage;
    }

    /**
     * 根据品牌ID获取系列列表
     *
     * @param brandId 品牌ID
     * @return 系列列表
     */
    @Override
    public List<VehicleSeries> listSeriesByBrandId(Long brandId) {
        // 检查品牌是否存在
        VehicleBrand brand = vehicleBrandMapper.selectById(brandId);
        if (brand == null) {
            throw new BusinessException("品牌不存在");
        }
        
        List<VehicleSeries> seriesList = list(new LambdaQueryWrapper<VehicleSeries>()
                .eq(VehicleSeries::getBrandId, brandId)
                .eq(VehicleSeries::getDeleted, 0)
                .orderByAsc(VehicleSeries::getCreateTime));
        
        // 设置品牌名称
        for (VehicleSeries series : seriesList) {
            series.setBrandName(brand.getName());
        }
        
        return seriesList;
    }
    
    /**
     * 根据品牌ID获取可用的系列列表（显示状态为1）
     *
     * @param brandId 品牌ID
     * @return 可用的系列列表
     */
    @Override
    public List<VehicleSeries> listAvailableSeriesByBrandId(Long brandId) {
        // 检查品牌是否存在
        VehicleBrand brand = vehicleBrandMapper.selectById(brandId);
        if (brand == null) {
            throw new BusinessException("品牌不存在");
        }
        
        List<VehicleSeries> seriesList = list(new LambdaQueryWrapper<VehicleSeries>()
                .eq(VehicleSeries::getBrandId, brandId)
                .eq(VehicleSeries::getDeleted, 0)
                .eq(VehicleSeries::getShowStatus, 1)
                .orderByAsc(VehicleSeries::getSort));
        
        // 设置品牌名称
        for (VehicleSeries series : seriesList) {
            series.setBrandName(brand.getName());
        }
        
        return seriesList;
    }
} 